package com.zyiot.bdapi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.zyiot.lbs.InitApplication;
import com.zyiot.lbs.TabListMapActivity;

/**
 * 百度云检索使用类
 * 
 * @author Lu.Jian
 * 
 */
public class LBSCloudSearch {

	private static String mTAG = "NetWorkManager";

	// 百度云检索API URI
	private static final String SEARCH_URI = "http://api.map.baidu.com/geosearch/poi?";
	private static final String LOCAL_URI = "http://api.map.baidu.com/geosearch/v2/local?";
	private static final String BOUND_URI = "http://api.map.baidu.com/geosearch/v2/bound?";
	private static final String NEARBY_URI = "http://api.map.baidu.com/geosearch/v2/nearby?";
	private static final String UPDATE_COLUMN = "http://api.map.baidu.com/geodata/v2/poi/update";
	public static final int LOCAL_CODE = 1;
	public static final int BOUND_CODE = 2;
	public static final int NEARBY_CODE = 3;
	// 云检索公钥
	private static String ak = "E93874284c56a50282ec0f3740db3d1e";

	private static String databox_id = "18238";

	private static int TIME_OUT = 12000;
	private static int retry = 3;
	private static boolean IsBusy = false;
	static String requestURL = null;
	/**
	 * 云检索访问
	 * 
	 * @param filterParams
	 *            访问参数，key为filter时特殊处理。
	 * @param handler
	 *            数据回调Handler
	 * @param networkType
	 *            手机联网类型
	 * @return
	 */

	public static boolean request(final HashMap<String, String> filterParams, final Handler handler, final String networkType) {
		if (IsBusy || filterParams == null)
			return false;
		IsBusy = true;

		new Thread() {
			@Override
			public void run() {
				int count = retry;
				while (count > 0) {
					try {
						// 根据过滤选项拼接请求URL
						String requestURL = SEARCH_URI;
						requestURL = requestURL + "scope=2" + "&" + "ak=" + ak;

						String filter = null;
						Iterator iter = filterParams.entrySet().iterator();
						while (iter.hasNext()) {
							Map.Entry entry = (Map.Entry) iter.next();
							String key = entry.getKey().toString();
							String value = entry.getValue().toString();

							if (key.equals("filter")) {
								filter = value;
							} else {
								requestURL = requestURL + "&" + key + "=" + value;
							}
						}
						if (filter != null) {
							requestURL = requestURL + "&filter=databox:" + databox_id + filter;
						} else {
							requestURL = requestURL + "&filter=databox:" + databox_id;
						}

						Log.d("TEST", "" + requestURL);
						HttpGet httpRequest = new HttpGet(requestURL);
						HttpClient httpclient = new DefaultHttpClient();
						httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
						httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);

						HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);

						if (networkType.equals("cmwap")) {
							HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
						} else if (networkType.equals("ctwap")) {
							HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
						}

						HttpResponse httpResponse = httpclient.execute(httpRequest);
						int status = httpResponse.getStatusLine().getStatusCode();
						if (status == HttpStatus.SC_OK) {

							String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
							Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_SUCC);
							msgTmp.obj = result;
							msgTmp.sendToTarget();
							break;
						} else {
							httpRequest.abort();
							Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_STATUS_ERROR);
							msgTmp.obj = "HttpStatus error";
							msgTmp.sendToTarget();
						}
					} catch (Exception e) {
						Toast.makeText(InitApplication.getInstance(), "网络异常，请检查网络后重试！", Toast.LENGTH_SHORT).show();
						System.exit(0);
						e.printStackTrace();
					}

					count--;
				}

				if (count <= 0 && handler != null) {
					Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_TIMEOUT);
					msgTmp.sendToTarget();
				}

				IsBusy = false;

			}
		}.start();

		return true;
	}

	/**
	 * 云检索访问
	 * 
	 * @param TYPE
	 *            检索类型
	 * @param filterParams
	 *            访问参数，key为filter时特殊处理。
	 * @param handler
	 *            数据回调Handler
	 * @param networkType
	 *            手机联网类型
	 * @return
	 */
	public static boolean request_V2(final HashMap<String, Object> filterParams, final Handler handler, final String networkType) {
		if (IsBusy || filterParams == null)
			return false;
		IsBusy = true;
		new Thread() {
			@Override
			public void run() {
				int count = retry;
				int TYPE = (Integer) filterParams.get("TYPE");
				// 根据过滤选项拼接请求URL
				switch (TYPE) {
				case LOCAL_CODE:
					requestURL = LOCAL_URI;
					break;
				case BOUND_CODE:
					requestURL = BOUND_URI;
					break;
				case NEARBY_CODE:
					requestURL = NEARBY_URI;
					break;
				}
				requestURL = requestURL + "ak=" + ak + "&" + "geotable_id=" + InitApplication.getGeotable_id() + InitApplication.getSortby();
				while (count > 0) {
					try {
						Iterator iter = filterParams.entrySet().iterator();
						while (iter.hasNext()) {
							Map.Entry entry = (Map.Entry) iter.next();
							String key = entry.getKey().toString();
							String value = entry.getValue().toString();
							if (key.equals("TYPE"))
								continue;
							requestURL = requestURL + "&" + key + "=" + value;
						}
						//Log.d("TEST","requestURL::"+requestURL);
						HttpGet httpRequest = new HttpGet(requestURL);
						HttpClient httpclient = new DefaultHttpClient();
						httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
						httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);
						HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);

						if (networkType.equals("cmwap")) {
							HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
						} else if (networkType.equals("ctwap")) {
							HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
						}

						HttpResponse httpResponse = httpclient.execute(httpRequest);
						int status = httpResponse.getStatusLine().getStatusCode();
						if (status == HttpStatus.SC_OK) {

							String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
							Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_SUCC);
							msgTmp.obj = result;
							msgTmp.sendToTarget();
							break;
						} else {
							httpRequest.abort();
							Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_STATUS_ERROR);
							msgTmp.obj = "HttpStatus error";
							msgTmp.sendToTarget();
						}
					} catch (Exception e) {
						Toast.makeText(InitApplication.getInstance(), "网络异常，请检查网络后重试！", Toast.LENGTH_SHORT).show();
						System.exit(0);
						e.printStackTrace();
					}

					count--;
				}

				if (count <= 0 && handler != null) {
					Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_TIMEOUT);
					msgTmp.sendToTarget();
				}

				IsBusy = false;

			}
		}.start();

		return true;
	}

	public static boolean UPDATE_COLUMN_V2(final String column_id, final String column_key, final String column_value, final Handler handler,
			final String networkType) {
		if (IsBusy || column_value == null)
			return false;
		IsBusy = true;

		new Thread() {
			@Override
			public void run() {
				int count = retry;
				requestURL = UPDATE_COLUMN ;//+ "ak=" + ak + "&geotable_id=" + InitApplication.geotable_id + "&id=" + column_id;
				while (count > 0) {
					try {
						//requestURL = requestURL + "&" + column_key + "=" + column_value;
						HttpPost httpRequest = new HttpPost(requestURL);
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
						//数据
						nameValuePairs.add(new BasicNameValuePair("ak", ak));
						nameValuePairs.add(new BasicNameValuePair("geotable_id", InitApplication.getGeotable_id()));
						nameValuePairs.add(new BasicNameValuePair("id", column_id));
						nameValuePairs.add(new BasicNameValuePair(column_key, column_value));
						// 设置字符集
						HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
//						Log.d("TEST","requestURL:"+requestURL+"nameValuePairs"+nameValuePairs);
						// 设置参数实体
						httpRequest.setEntity(entity);
						HttpClient httpclient = new DefaultHttpClient();
						httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
						httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);
						HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);

						if (networkType.equals("cmwap")) {
							HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
						} else if (networkType.equals("ctwap")) {
							HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
						}
						HttpResponse httpResponse = httpclient.execute(httpRequest);
						int status = httpResponse.getStatusLine().getStatusCode();
						if (status == HttpStatus.SC_OK) {
							String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
							Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_SUCC);
							msgTmp.obj = result;
							msgTmp.sendToTarget();
							break;
						} else {
							httpRequest.abort();
							Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_STATUS_ERROR);
							msgTmp.obj = "HttpStatus error";
							msgTmp.sendToTarget();
						}
					} catch (Exception e) {
						Toast.makeText(InitApplication.getInstance(), "网络异常，请检查网络后重试！", Toast.LENGTH_SHORT).show();
						System.exit(0);
						e.printStackTrace();
					}

					count--;
				}

				if (count <= 0 && handler != null) {
					Message msgTmp = handler.obtainMessage(TabListMapActivity.MSG_NET_TIMEOUT);
					msgTmp.sendToTarget();
				}

				IsBusy = false;
			}
		}.start();

		return true;
	}
}
